package wxpay

import (
	"bytes"
	"encoding/xml"
	"io/ioutil"
	"net/http"
	"strings"

	uuid "github.com/satori/go.uuid"
)

type DownloadBillReq struct {
	AppId    string `xml:"appid"`
	MchId    string `xml:"mch_id"`
	NonceStr string `xml:"nonce_str"`
	Sign     string `xml:"sign"`
	BillDate string `xml:"bill_date"`
}

func WxDownloadBill(appId string, billDate string) (WxPayResponse, error) {
	var downloadBillReq DownloadBillReq
	downloadBillReq.AppId = appId
	downloadBillReq.MchId = MchId
	sourceUuid := uuid.NewV4()
	formatUuid := strings.Replace(sourceUuid.String(), "-", "", -1)
	downloadBillReq.NonceStr = formatUuid
	downloadBillReq.BillDate = billDate

	var mReqMap map[string]interface{}
	mReqMap = make(map[string]interface{}, 0)
	mReqMap["appid"] = downloadBillReq.AppId
	mReqMap["mch_id"] = downloadBillReq.MchId
	mReqMap["nonceStr"] = downloadBillReq.NonceStr
	mReqMap["bill_date"] = downloadBillReq.BillDate
	downloadBillReq.Sign = WxPayCalcSign(mReqMap, MchSecret)

	xmlReq, err := xml.Marshal(downloadBillReq)
	if err != nil {
		return WxPayResponse{}, err
	}
	strReq := string(xmlReq)
	strReq = strings.Replace(strReq, "DownloadBillReq", "xml", -1)
	xmlReq = []byte(strReq)

	request, err := http.NewRequest("POST", "https://api.mch.weixin.qq.com/pay/downloadbill", bytes.NewReader(xmlReq))
	if err != nil {
		return WxPayResponse{}, err
	}
	request.Header.Set("Accept", "application/xml")
	request.Header.Set("Content-Type", "application/xml;charset=utf-8")

	httpClient := http.Client{}
	response, err := httpClient.Do(request)
	if err != nil {
		return WxPayResponse{}, err
	}

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return WxPayResponse{}, err
	}

	var payResponse WxPayResponse
	err = xml.Unmarshal(responseBody, &payResponse)
	if err != nil {
		return WxPayResponse{}, err
	}

	return payResponse, nil
}
